<template>
  <view class="pages">
    <!-- <view class="all_num">评论（{{total}}）</view> -->
    <view class="comment" id="comment" v-for="(item, index) in commentList" :key="index" @click="toCommenta(item, index)">
      <view class="comment_box">
        <view class="comment_head">
          <view class="comment_head_l" @click.stop="toMypage(item)">
            <u--image :src="item.avatar" width="62rpx" height="62rpx" radius="50%">
              <template #error class="flex-center-center">
                <view class="ic-error">
                  <u-icon name="photo" size="20"></u-icon>
                </view>
              </template>
            </u--image>
          </view>
          <!-- 一级回复 -->
          <view class="comment_head_r" style="  border-bottom: 1rpx solid #e6e6e6;padding-bottom: 10rpx;">
            <view class="comment_nickname">
              <view class="comment_head_r_name">
                <text class="text-overflow-ep">{{ item.nickname || '匿名用户' }}</text>
                <view class="user_tags">
                  <image v-if="item?.app_user_tag=='official'"
                    src="https://ossresource.miyingbl.com/uploads/20240308/072661a99870e1fcfba1d1df6d8ddd35.png"></image>
                  <image v-if="item?.app_user_tag=='doctor'"
                    src="https://ossresource.miyingbl.com/uploads/20240308/dbb99ae497e429ae87f740fb0f64a57f.png"></image>
                  <text class="u-line-1 "> {{forMatStatus(item?.identity_status)}}</text>
                </view>
              </view>
              <!-- 点赞图标 -->
              <view class="comment_box_zan" @click.stop="praise(item)">
                <image src="https://ossresource.miyingbl.com/def/9f361202405231506404750.png" class="icons"
                  v-if="item.is_zan == 1"></image>
                <image src="https://ossresource.miyingbl.com/def/29cbd202405231506398795.png" class="icons" v-else>
                </image>
                <view class="comment_box_zan_num">
                  {{ item.zan_number ? item.zan_number : 0 }}
                </view>
              </view>
            </view>
            <view class="comment_ct_r_text" @longpress="longpressCommenta(item, index,commentList)"> {{ item.comment_text || '' }}</view>
            <view class="comment_ct_r_time">{{ item.create_time || '' }}<text class="address"> {{item.province}}</text><text>回复</text></view>

            <view class="comment_boxc" v-for="(items, indexs) in item.comment_list" :key="indexs"
              v-show="item.comment_list && indexs < 2" @click.stop="toCommentb(items, index, false, indexs)">
              <view class="comment_head">
                <view class="comment_head_l"  @click.stop="toMypage(items)">
                  <u--image :src="items.avatar" width="62rpx" height="62rpx" radius="50%">
                    <template #error class="flex-center-center">
                      <view class="ic-error">
                        <u-icon name="photo" size="20"></u-icon>
                      </view>
                    </template>
                  </u--image>
                </view>
                <!-- 二级回复 -->
                <view class="comment_head_r">
                  <view class="comment_nickname">
                    <view class="comment_head_r_name">
                      <text class="text-overflow-ep">{{ items.nickname || '匿名用户' }}</text>
                      <view class="user_tags">
                        <image v-if="items?.app_user_tag=='official'"
                          src="https://ossresource.miyingbl.com/uploads/20240308/072661a99870e1fcfba1d1df6d8ddd35.png"></image>
                        <image v-if="items?.app_user_tag=='doctor'"
                          src="https://ossresource.miyingbl.com/uploads/20240308/dbb99ae497e429ae87f740fb0f64a57f.png"></image>
                        <text class="u-line-1 "> {{forMatStatus(items?.identity_status)}}</text>
                      </view>
                    </view>
                    <view class="comment_box_zan" @click.stop="praise(items)">
                      <image src="https://ossresource.miyingbl.com/def/9f361202405231506404750.png" class="icons"
                        v-if="items.is_zan == 1"></image>
                      <image src="https://ossresource.miyingbl.com/def/29cbd202405231506398795.png" class="icons" v-else>
                      </image>
                      <view class="comment_box_zan_num">
                        {{ items.zan_number ? items.zan_number : 0 }}
                      </view>
                    </view>
                  </view>
                  <view class="comment_ct_r_text" @longpress="longpressCommenta(items, indexs,item.comment_list)"> <text v-if="items.to_user_name">回复<text
                              style="color:#969696;padding-left:10rpx">{{items.to_user_name}}：</text></text> {{ items.comment_text || '' }}</view>
                  <view class="comment_ct_r_time">{{ items.create_time || '' }}<text class="address"> {{item.province}}</text> <text>回复</text></view>
                </view>
              </view>
            </view>
            <view class="comment_boxc" v-for="(items, indexs) in item.comment_list" :key="indexs"
              v-show="indexs >= 2 && item.show" @click.stop="toCommentb(items, index, false, indexs)">
              <view class="comment_head">
                <image class="comment_head_l" :src="items?.avatar || ''"  @click.stop="toMypage(items)"/>
                <view class="comment_head_r">

                  <view class="comment_nickname">
                    <view class="comment_head_r_name">
                      <text class="text-overflow-ep">{{ items.nickname || '匿名用户' }}</text>
                      <view class="user_tags">
                        <image v-if="items?.app_user_tag=='official'"
                          src="https://ossresource.miyingbl.com/uploads/20240308/072661a99870e1fcfba1d1df6d8ddd35.png"></image>
                        <image v-if="items?.app_user_tag=='doctor'"
                          src="https://ossresource.miyingbl.com/uploads/20240308/dbb99ae497e429ae87f740fb0f64a57f.png"></image>
                        <text class="u-line-1 "> {{forMatStatus(items?.identity_status)}}</text>
                      </view>
                    </view>
                    <view class="comment_box_zan" @click.stop="praise(items)">
                     <image src="https://ossresource.miyingbl.com/def/9f361202405231506404750.png" class="icons"
                       v-if="items.is_zan == 1"></image>
                     <image src="https://ossresource.miyingbl.com/def/29cbd202405231506398795.png" class="icons" v-else>
                     </image>
                      <view class="comment_box_zan_num">{{ items.zan_number }}</view>
                    </view>
                  </view>
                  <view class="comment_ct_r_text" @longpress="longpressCommenta(items, indexs,item.comment_list)"> <text v-if="items.to_user_name">回复<text
                              style="color:#969696;padding-left:10rpx">{{items.to_user_name}}：</text></text>{{ items.comment_text || '' }}</view>
                  <view class="comment_ct_r_time">{{ items.create_time || '' }} <text class="address"> {{item.province}}</text><text>回复</text></view>
                </view>
              </view>

            </view>
            <view class="comment_boxc_more comment_boxc_more1" @click.stop="getMore(index)"
              v-if="item.comment_list && item.comment_list.length > 2">
              {{ item.show ? '收回' : '展开更多回复' }}
            </view>
          </view>
        </view>
      </view>
    </view>
      <view v-if="(total==commentList.length)&&total!=0" class="bottomLine">到底了~</view>
  </view>

  <view class="kong"><view style="height: 90rpx;"></view></view>
  <view class="footer">
    <view class="footer_input" @click="toCom()">
       <u-icon name='edit-pen' size='20' color='999999'></u-icon> <text style="padding-left:10rpx;" >我来评论</text>
    </view>
  </view>
  <!-- 评论输入框 -->
  <TextareaComment ref="textareaCommentRef" v-model:showInputPop="showInputPop" @closeInputPop="closeInputPop" @commentSuccess="commentSuccess" :detail='detail' :type="2" >
  </TextareaComment>
  <h-login ref="login"></h-login>
</template>

<script setup lang="ts">

  import TextareaComment from "@/components/BottomComment/TextareaComment"
  import BottomComment from "@/components/BottomComment/BottomComment"
  import { navigateTo, showToast } from '@/utils'
  import {
    ref,
    reactive,
    nextTick
  } from 'vue'
  import {
    onLoad,
    onPullDownRefresh,
    onReachBottom
  } from '@dcloudio/uni-app'
  import {
    getCreateUser,coupeDetailsApi,coupeCommentsApi,followUserApi,articleOperateApi,trendCommentDelApi,trendCommentLikeApi
  } from '@/api/social'

  import {
    getTrendsInfo,
    getTrendsComments,
    trendsComment,
    trendsZan,
    trendsCollect,
    trendsCommentDel
  } from '@/api/trends'
  import {
    useMemberStore,useSystemStore
  } from '@/stores'
  const system = useSystemStore()
  const userStore = useMemberStore()
  var detail = ref({})
  var userInfo = ref({})
  var total = ref(0)
  var commentList = ref([])
  var commonId = ref("")
  const store = useMemberStore()
  const token = store?.token
  userInfo.value = store?.userInfo
  console.log(userInfo.value)
  var commentShow = ref(false)
  var upIndex = 0
  var childIndex = 0
  var commentText = ref("")
  var commentPostText = ref("")
  var upRow = ref({})
  var child = ref({})
  var isLoading = ref(false)
  const trends_type=ref(0)
  onLoad(({
    id,
    type
  }) => {
    commonId.value = id
    trends_type.value=type
    getDetail(id)
    getCom(id)
  })
  async function getDetail(id) {
    const res = await coupeDetailsApi({
      article_id: id,
      type:1
    })
    var data = res.data;
    detail.value = data
  }
  const page=ref(1)
  const last_page=ref(0)
  async function getCom(id) {
    const ress = await coupeCommentsApi({
      id: commonId.value,
      page:page.value,
      limit:10,
      type:1
    })
    total.value = ress.data.total;
    commentList.value =page.value==1? ress.data.data: commentList.value.concat(ress.data.data)
    last_page.value=ress.data.last_page
  }
  onReachBottom(()=>{
    if(last_page.value>page.value){
      page.value++
      getCom()
    }
  })
  function getMore(index) {
    commentList.value[index].show = !commentList?.value[index].show
  }
  // 评论》点赞
   async function praise(row) {

     const res = await trendCommentLikeApi({
       id: detail.value.id, //动态id
       comment_id: row.id, //目标id
     })
     if (res.msg == '自己就不用给自己点赞了哈~') {
       // 给自己评论
       uni.showToast({
         title: res.message,
         icon: 'none',
       })
     } else {
       if (row.is_zan == 1) {
         row.zan_number--
         row.is_zan = 0
         uni.showToast({
           title: res.message,
           icon: 'none',
         })
       } else {
         uni.showToast({
           title: res.message,
           icon: 'none',
         })
         row.zan_number++
         row.is_zan = 1
       }
     }
   }
   const login=ref(false)
   async function praisea(row) {
     if (!token) {
       login.value.open()
       return false
     }
     const res = await trendsZan({
       id: row.id,
       zan_type: 1,
     })

     if (res.msg == '自己就不用给自己点赞了哈~') {
       // 给自己评论
       uni.showToast({
         title: res.msg,
         icon: 'none',
       })
     } else {
       if (row.is_zan == 1) {
         row.zan_number--
         row.is_zan = 0
         detail.is_zan = 0
       } else {
         row.zan_number++
         row.is_zan = 1
         detail.is_zan = 1
       }
     }
     uni.setStorageSync('socialDetail', row)
   }

   async function toppicCang(row) {
     if (!token) {
       login.value.open()
       return false
     }
     const res = await trendsCollect({
       id: row.id,
       type: trends_type.value,
     })
     if (row.is_collect == 0) {
       row.is_collect = 1
       row.collect_number++
     } else {
       row.is_collect = 0
       row.collect_number--
     }
     uni.showToast({
       title: res.msg,
       icon: 'none',
       duration: 2000,
     })
     uni.setStorageSync('socialDetail', row)
   }


   // 回复一级评论
   function toCommenta(row, index, str = '') {
     console.log(token,111)
     if (!token) {
       login.value.open()
       return false
     }
     articleCommentInputFocus(2,row)
     upRow.value = row
     upIndex = index
     child.value = ''
     childIndex = ''
   }
  // 回复二级评论
   function toCommentb(row, index, isChild, childIndex) {
     if (!token) {
       login.value.open()
       return false
     }
     articleCommentInputFocus(2,row)
     upRow.value = row
     upIndex = index
     child.value = isChild
     childIndex = childIndex
     if (!isChild) {
       commentShow.value = true
     }
   }

  const commentSuccess = ({ type, content, id }) => {
    console.log(type, content)
      console.log(userInfo.value)
    if (type == 1) {
      // 发表评论
      commentList.value.unshift({
        comment_text: content,
        create_time: '刚刚',
        avatar: userInfo.value.avatar,
        nickname: userInfo.value.name,
        show_btn: true,
        comment_list: [],
        zan_number: 0,
        is_zan: 0,
        user_id: userInfo.value.uid,
        // app_user_tag: userInfo.value.app_user_tag,
        identity_status: userInfo.value.identity_status,
        province: system?.location?.province || '',
        app_user_tag: 'doctor',
        id,
      })
      detail.value.comment_number++
      total.value++
      uni.setStorageSync('socialDetail', upRow.value)
      getHeight()
    } else {
      // 回复评论
      commentList.value[upIndex].comment_list.unshift({
        comment_text: content,
        avatar: userInfo.value.avatar,
        create_time: '刚刚',
        to_user_name: upRow.value.nickname,
        p_nickname: upRow.value.nickname,
        app_user_tag: 'doctor',
        nickname: userInfo.value.name,
        p_uid: upRow.value.uid,
        user_id: userInfo.value.uid,
        comment_num: 0,
        show_btn: true,
        comment: [],
        zan_number: 0,
        is_zan: 0,
        comment_id: upRow.value.id,
        // app_user_tag: userInfo.value.app_user_tag,
        identity_status: userInfo.value.identity_status,
        province: system?.location?.province || '',
        id
      })
      detail.value.comment_number++
    }
  }

   // 评论输入框组件
   const textareaCommentRef = ref()

   // 新建评论弹窗
   const showInputPop = ref(false)

   // 文章评论聚焦
   const articleCommentInputFocus = (type: number, e?: CommentRootList) => {
     showInputPop.value = true
     nextTick(() => {
       textareaCommentRef.value && textareaCommentRef.value.inputFocus(type, e)
     })
   }
   function toCom() {
     if (!token) {
       login.value.open()
       return false
     } else {
       articleCommentInputFocus(1)
     }
   }

   // 关闭输入框
   const closeInputPop = () => {
     showInputPop.value = false
   }
   function forMatStatus(status) {
     let text = ''
     switch (status) {
       case 0:
         text = ''
         break
       case 1:
         text = '记经期'
         break
       case 2:
         text = '备孕中'
         break
       case 3:
         text = '怀孕中'
         break
       case 4:
         text = '宝宝已出生'
         break
       case 5:
         text = '未婚'
         break
       case 6:
         text = '准爸'
         break

       case 7:
         text = '爸爸'
         break
       case 8:
         text = '生产育儿'
         break
       case 9:
         text = '慢病'
         break
       case 10:
         text = '其他'
         break
     }
     return text
   }
   const longpressCommenta= (row,index,list) =>{
        console.log(list)
        if(row.user_id==userInfo.value.uid){
          uni.showModal({
            title: '温馨提示',
            content: '您确定要删除此条评论吗？',
            showCancel: true,
            success: (res) => {
              if (res.confirm) {
                trendCommentDelApi({
                  id: row.id
                }).then(result => {
                  if (result.code ==200) {
                    list.splice(index, 1)
                    uni.showToast({
                      title: result.message,
                      icon: 'none'
                    })
                  } else {
                    uni.showToast({
                      title: result.message,
                      icon: 'none'
                    })
                  }
                })
              }
            },
          })
        }
     }
 function getHeight() {
    uni
      .createSelectorQuery()
      .select('#comment')
      .boundingClientRect((rect) => {
        console.log(rect)
        var num = rect?.top
        autoScroll(num)
      })
      .exec()
  }

  function autoScroll(height) {
    uni.pageScrollTo({
      scrollTop: height,
      duration: 300,
    })
  }
  function toMypage(item) {
    console.log(item)
    if (item?.user_info?.app_user_tag||item?.app_user_tag) {
      let app_user_tag=item?.user_info?.app_user_tag||item?.app_user_tag
      let uid=item?.uid||item?.user_id
      if(uid == userStore?.userInfo.uid){
        navigateTo(`/pages-users/my-page/index?is_self=0&uid=${uid}&type=dt&tag=${app_user_tag}`)
      }else {
        navigateTo(`/pages-users/my-page/official-doctor-home?is_self=0&uid=${uid}&type=dt&tag=${app_user_tag}`)
      }
    } else {
      navigateTo(`/pages-users/my-page/other-index?is_self=0&uid=${uid}&type=dt&tag=${app_user_tag}`)
    }
  }
</script>
<style>
  page {
    background: #F5F6F8;
  }
</style>
<style lang="scss" scoped>
  .pages {
    padding:0 20rpx 25rpx;
    box-sizing: border-box;
    // border-top:10rpx solid #F6F6F6;
    width: 700rpx;
    background: #FFFFFF;
    border-radius: 20rpx;
    margin: 20rpx auto 0;
  }

  .all_num {
    font-size: 28rpx;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 60rpx;
  }

  .image-list {
    width: 100%;
    margin: 22rpx 0;

    .scroll-content {
      height: 100%;
      display: flex;
      flex-wrap: nowrap;

      .ic-error {
        width: 100%;
        padding-left: 77rpx;
        font-size: 28rpx;
        display: flex;
      }
    }

    ::v-deep .u-transition {
      margin-right: 55rpx;
    }
  }
 .comment {
      width: 100%;
      padding-top: 24rpx;
      box-sizing: border-box;

      .comment_box {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;

          .comment_head {
              width: 100%;
              display: flex;
              flex-wrap: wrap;
              justify-content: space-between;

              .comment_head_l {
                  width: 62rpx;
                  height: 62rpx;
                  border-radius: 50%;
              }

              .comment_head_r {
                  width: 580rpx;
                  &.commentBorder{
                    border-bottom: 1rpx solid #e6e6e6;
                    // &:nth-last-child(1){
                    //   border:none
                    // }
                  }
                  .comment_nickname {
                      display: flex;
                     align-items:center;
                  }

                  .comment_head_r_name {
                      font-size: 28rpx;

                      font-weight: 500;
                      color: #333333;
                      flex: 1;
                      align-items: center;
                  }

                  .comment_ct_r_text {
                      font-size: 28rpx;

                      font-weight: 500;
                      color: #333333;
                      line-height: 40rpx;
                      margin-top:10rpx;
                      width:504rpx;
                  }

                  .comment_ct_r_time {
                      font-size: 22rpx;

                      font-weight: 500;
                      color: #999;
                      line-height: 33rpx;
                      padding-top: 5rpx;

                      text {
                          color: #333333;
                          margin-left: 10rpx;
                      font-size: 26rpx;
                      }
                      .address{
                        color: #999;
                        margin-right: 15rpx;
                      font-size: 22rpx;
                      }
                  }
              }
          }
      }

      .comment_boxc {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;
          padding: 15rpx 0 0 0;
          width: 100%;

          .comment_head {
              display: flex;
              flex-wrap: wrap;
              justify-content: space-between;
              width: 580rpx;

              .comment_head_l {
                  width: 62rpx;
                  height: 62rpx;
                  border-radius: 50%;
              }

              .comment_head_r {
                  width:500rpx;

                  .comment_head_r_name {
                      font-size: 24rpx;

                      font-weight: 500;
                      color: #333333;
                      // display: flex;
                  }

                  .comment_ct_r_text {
                      font-size: 26rpx;

                      font-weight: 500;
                      color: #333333;
                      line-height: 1.5;
                  }

                  .comment_ct_r_time {
                      font-size: 22rpx;

                      font-weight: 500;
                      color: #999;
                      line-height: 33rpx;

                      text {
                          color: #333333;
                          margin-left: 10rpx;
                      }
                  }
              }
          }
      }

      .comment_box_zan {
          text-align: right;

          .comment_box_zan_img {
              width: 40rpx;
              height: 40rpx;
          }

          .comment_box_zan_num {
              font-weight: 500;
              font-size: 22rpx;
              color: #333333;
              text-align: center;
          }
          .icons{
            width:28rpx;
            height:28rpx;
            display:block
          }
      }
      &:nth-last-child(2){
       .comment_box .comment_head .comment_head_r.commentBorder{
          border:none
       }
      }

  }

   .comment_boxc_more {
     font-size: 26rpx;
     font-family: PingFang SC-Regular, PingFang SC;
     font-weight: 400;
     color: #666666;
     text-align: center;

     .empty_image {
       width: 323rpx;
       height: 207rpx;
       margin-top: 100rpx;
     }
   }
   .comment_boxc_more1{
     font-family: PingFang SC, PingFang SC;
     font-weight: 500;
     font-size: 28rpx;
     color: #00C1B9;
     text-align: left;
     padding-left: 82rpx;
   }

   .kong{
      padding:15rpx ;
      // height: 120rpx;
      padding-bottom: calc(15rpx + constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
      padding-bottom: calc(15rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/
   }
  .footer {
    width: 100%;
    box-sizing: border-box;
    padding: 15rpx 25rpx;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    position: fixed;
    bottom: 0;
    left: 0;
    background: #fff;
    padding-bottom: calc(15rpx + constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
    padding-bottom: calc(15rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/


    .footer_input {
      width: 100%;
      height: 70rpx;
      background: #F8F8F8;
      border-radius: 36rpx;
      border: 1rpx solid #E6E6E6;
      font-size: 26rpx;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #999999;
      box-sizing: border-box;
      padding: 0 20rpx;
      border:none;
      display:flex;
      align-items:center;
      flex-direction: row;
    }

    .send-btn {
      width: 142rpx;
      height: 72rpx;
      background: #0074FC;
      border-radius: 36rpx;
      font-size: 28rpx;

      font-weight: 500;
      color: #FFFFFF;
      line-height: 72rpx;
      text-align: center;
    }
  }

  .footera {
    width: 100%;
    height: 156rpx;
    box-sizing: border-box;
    padding: 44rpx 24rpx;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    background: #FFF;
    box-shadow: 0rpx -2rpx 7rpx 0rpx rgba(0, 0, 0, 0.09);

    .footer_input {
      width: 530rpx;
      height: 72rpx;
      background: #F8F8F8;
      border-radius: 36rpx;
      border: 1rpx solid #E6E6E6;
      font-size: 28rpx;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #999999;
      box-sizing: border-box;
      padding: 0 20rpx;
    }

    .send-btn {
      width: 142rpx;
      height: 72rpx;
      background: #0074FC;
      border-radius: 36rpx;
      font-size: 28rpx;

      font-weight: 500;
      color: #FFFFFF;
      line-height: 72rpx;
      text-align: center;
    }
  }
  .bottomLine{
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 26rpx;
    color: #A7A7A7;
    text-align: center;
    margin-top: 30rpx;
  }
  .user_tags {
    display: flex;
    align-items: center;

    text {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 22rpx;
      color: #969696;
      margin-right: 10rpx;
    }

    image {
      width: 113rpx;
      height: 27rpx;
      display: block;
      margin-right: 10rpx;
    }
  }
</style>
